# 导包
import bcrypt
import requests
from config.gloabl import GlToken


def get_key():
    # 测试环境
    password = b"Creek)Ew&IzihGz9@pyb)qm"
    # 正式环境
    # password = b"Creek)EkmkAwRko3u8&PY!"
    hashed = bcrypt.hashpw(password, bcrypt.gensalt())
    return hashed.decode('utf-8')


# print(get_key())


# 新建类 登录接口对象、并将token存入全局
class UserLogin(object):
    # 新建方法 登陆方法
    @classmethod
    def api_post_login(cls, url, user):
        # 请求头定义
        headers = {"Content-Type": "application/json"}
        # data定义
        data = {
            "email": user,
            "key": get_key(),
            "password": "TtToBhIcpiuSRrhtP58H3wj2WZxp9TMpBNLkBSYw8fCNWTqBby/HtiKCgucRKta8Mc16SL+FuUHn7G40rx7OAwItM/CF6L0veZBJYBKF7o8XZxuuV//6LaJ21CQfNO5jIZJbWs9Lj2i/llfc56AfYfYB46ktaHUvuf7ggKs8haGv+FeUP+NyyrNTFw4Cw/pve1fA14h9DtOat0X7o52jVW6tqCpHu0EpO2wgoXLE8lmJSKiflzsPcsIHKOX5LBAxEq+sziq+gFrcqAIpGzL1U33dGHorLzIiTUzJ5Fi5wn7KVdOY4kzzWqE1pCxgkhoAcdyOK7PSHTxrXR7hVI+dug==",
            "customerCode": "XCKJ",
            "mobileId": "c9febf06aa66e467"
        }
        resp = GlToken.session.post(url=url, headers=headers, json=data)
        try:
            result = resp.json()
            token = result['data']['token']
            # config.token = token
            GlToken.token = token
            print("已存入的token", GlToken.token)
        finally:
            print("程序执行完毕。")
        # except Exception as e:
        #     print("解析 token 时出错:", e)
        # 调用post方法
        return requests.post(url=url, headers=headers, json=data)

    #获取用户信息方法
    @classmethod
    def api_userinfo(cls, url):
        headers = {"Content-Type": "application/json", "Authorization": f"{GlToken.token}"}
        print(GlToken.token)
        # 调用get请求
        return requests.get(url=url, headers=headers)
